#include <iostream>
#include <vector>
#include <functional>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

long long count = 0;

typedef std::function<void()> func;
std::vector<func> trace_back;

void showCount()
{
    std::cout << "[" << getpid() << "]# " << "final count:" << count << std::endl;
}

void showLog()
{
    std::cout << "[" << getpid() << "]# " << "This is a log function" << std::endl;
}

void useLog()
{
    pid_t id = fork();
    if(id == 0)
    {
        std::cout << "[" << getpid() << "]# " << std::flush;
        execlp("who", "who", nullptr);
        std::cout << "run here ... " << std::endl;
        exit(0);
    }

    wait(nullptr);
}

void load()
{
    trace_back.push_back(showCount);
    trace_back.push_back(showLog);
    trace_back.push_back(useLog);
}

void alarm_handler(int)
{
    // std::cout << "[" << getpid() << "], alarm reaction, count:" << count << std::endl;
    // exit(0);

    for(const auto& func : trace_back)
    {
        func();
    }

    exit(0);
}

int main()
{
    alarm(1);  // 定义时钟，倒计时1s
    signal(SIGALRM, alarm_handler);   // 重新注册时钟信号处理函数

    load();   // 载入回调函数

    // cpu算力测试
    while(true)
    {
        ++count;
    }

    return 0;
}